from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
from meiduo01.models import *
from meiduo01.ser import ShowAddressSer


# Create your views here.

class Home(APIView):
    def get(self, request):
        # 获取一级分类
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list1 = []
        for i in cates:
            dict1 = {}
            dict1['id'] = i.id
            dict1['name'] = i.name
            # 获取二级
            two = i.subs.all()  # 反查询
            twolist = []
            for j in two:
                twodict = {}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three, many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)
            dict1['subs'] = twolist
            list1.append(dict1)
            # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods = []
        for j in cates:
            dict = {}
            dict['id'] = j.id
            dict['name'] = j.name
            dict['pic'] = str(j.pic)
            two = j.subs.all()
            twoser = CateSer(two, many=True)
            dict['two'] = twoser.data
            three = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = CateSer(three, many=True)
            dict['three'] = threeser.data
            # 获取商品,排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')  # 点那个排序那个
            topid = request.GET.get('topid')  # 顶级id
            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()
            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by('-' + sorted).all()
            gser = GoodSer(goods, many=True)
            dict['goods'] = gser.data
            categoods.append(dict)
        return Response({"code": 200, "catelist": list1, "categoods": categoods})


class XiangAPI(APIView):
    def get(self, request):
        id = request.GET.get('id')
        good = Goods.objects.filter(id=id).first()
        ser = GoodSer(good)
        return Response({"code": 200, "list": ser.data})


class CartM(APIView):
    def post(self, request):
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = request.data.get('number')
        cat = Cart.objects.filter(user_id=userid, goods_id=goodsid).first()
        if cat:
            cat.number += number
            cat.save()
            return Response({"code": 200})
        else:
            # Cart.objects.create(user_id=userid,goods_id=goodsid,number=number)
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code": 200})
            else:
                print(ser.errors)
                return Response({"code:21102"})

    def get(self, request):
        user = request.GET.get('user')
        cart = Cart.objects.filter(user_id=user).all()
        allm = Cart.objects.filter(user_id=user).count()  # 共几个商品种类
        ser = ShowCartSer(cart, many=True)
        allmoney = 0
        allstings = 0
        allchack = True
        for i in ser.data:
            if i['is_checked'] == True:
                allmoney += int(i['number']) * float(i['goods']['price'])
                allstings += int(i['number'])
            if i['is_checked'] == False:
                allchack = False
        return Response({"code": 200, "list": ser.data, "numm": allm, "allchack": allchack, "allmoney": allmoney,
                         "allstings": allstings})

    def delete(self, request):
        id = request.GET.get('id')
        Cart.objects.filter(id=id).delete()
        return Response({"code": 200, })
    # 单选多选


class DianAPI(APIView):
    def put(self, request):
        id = request.GET.get('id')
        userid = request.GET.get('user')
        aa = Cart.objects.filter(user_id=userid, id=id).first()
        if aa.is_checked == False:
            aa.is_checked = True
            aa.save()
            return Response({"code": 200})
        elif aa.is_checked == True:
            aa.is_checked = False
            aa.save()
            return Response({"code": 200})
        return Response({"code": 200})

    def get(self, request):
        userid = request.GET.get('user')
        allchack = request.GET.get("allchack")
        if allchack == 'true':
            Cart.objects.filter(user_id=userid).update(is_checked=True)
        else:
            Cart.objects.filter(user_id=userid).update(is_checked=False)
        return Response({"code": 200})

    # 按钮加减
    def post(self, request):
        id = request.data.get('id')
        type = request.data.get('type')
        userid = request.data.get('user')
        zz = Cart.objects.filter(id=id, user_id=userid).first()
        if type == 1:
            zz.number += 1
            zz.save()
        elif type == 2:
            zz.number -= 1
            zz.save()
        return Response({"code": 200})


class Getshop(APIView):
    def get(self, request):
        userid = request.GET.get('user')
        cart = Cart.objects.filter(user_id=userid, is_checked=True).all()
        ser = ShowCartSer(cart, many=True)
        allnum = 0  # 总数量
        allmonery = 0  # 总价钱
        for i in ser.data:
            if i['is_checked'] == True:
                allnum += i['number']
                allmonery += float(i['goods']['price']) * int(i['number'])
        return Response({"code": 200, "list": ser.data, "allnum": allnum, "allmonery": allmonery})


# 订单
import random
import datetime
from django.db import transaction


class OrederAPI(APIView):
    @transaction.atomic
    def post(self, request):
        # 获取userid
        userid = request.data.get('user')
        pay_money = request.data.get('pay_money')  # 支付方式
        addressaddid = request.data.get('addressaddid')  # 地址id，选的是那个地址
        # 根据userid查询购物车中已经选中的记录
        cart = Cart.objects.filter(user_id=userid, is_checked=True).all()
        cartser = ShowCartSer(cart, many=True)
        # 遍历购物车求出总价钱
        total_amount = 0  # 总价钱
        for i in cartser.data:
            total_amount += i['number'] * float(i['goods']['price'])
        # 生成订单号
        order_no = datetime.datetime.strftime(datetime.datetime.now(), '%Y%M%D%H%M%S') + str(userid) + str(
            random.randint(1000, 9999))
        # 查找地址构造地址信息
        add = Address.objects.filter(id=addressaddid).first()
        addressSer = ShowAddressSer(add)
        address = addressSer.data
        addressStr = str(address['province']['name']) + ' ' + str(address['city']['name']) + ' ' + str(
            address['area']['name']) + ' ' + str(address['address']) + ' ' + str(address['receive']) + ' ' + str(
            address['mobile'])
        datam = {'order_no': order_no, 'user': userid, 'address': addressStr, 'total_amount': total_amount,
                 'pay_method': pay_money}
        sid = transaction.savepoint()
        try:
            ser = OrderInfoSer(data=datam)
            if ser.is_valid():
                ser.save()
                # 生成订单详情
                for i in cartser.data:
                    detaildata = {'order': order_no, "goods": i['goods']['id'], 'goodsname': i['goods']['name'],
                                  'images': i['goods']['pic'], 'count': i['number'],
                                  'price': float(i['goods']['price']), 'user': userid}
                    # 调用序列化器添加订单详情
                    mser = OrderDetailSer(data=detaildata)
                    if mser.is_valid():
                        mser.save()
            # 购物车删除已经生成订单的记录
            Cart.objects.filter(user_id=userid, is_checked=True).delete()
            transaction.savepoint_commit(sid)
            return Response({"code": 200, "order_no": order_no, "tmoney": total_amount})
        except:
            # 事务回滚
            transaction.savepoint_rollback(sid)
            return Response({'code': 20010})


class Dingdan(APIView):
    def get(self,request):
        userid = request.GET.get('user')
        orderdetail = OrderDetail.objects.filter(user_id=userid).first()
        ser = OrderDetailSer(orderdetail)
        return Response({"code":200,"list":ser.data})










